package com.welab.springcloud.demo.gateway.filter;


import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.welab.springcloud.demo.api.AuthApi;
import com.welab.springcloud.demo.dto.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;


@Slf4j
@Component
@RefreshScope
public class AccessTokenFilter extends ZuulFilter {

	private static final String PARAM_TOKEN = "token";

	@Value("${system.config.accessTokenFilter.ignore}")
	private String ignoreUrl;

	@Value("${system.config.black.list}")
	private String blackList;

	@Autowired
	private AuthApi authApi;

	@Override
	public Object run() {

		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		String token = request.getHeader(PARAM_TOKEN);
		if (StringUtils.isBlank((token))) {
			token = request.getParameter(PARAM_TOKEN);
		}
		log.info("userToken:{}", token);
		log.info("blackList:{}", blackList);

		if(StringUtils.isEmpty(token)){
			requestContext.setSendZuulResponse(false);
			requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
		}

		ResponseResult<Boolean> authResult = authApi.parseToken(token);
		log.info("parseToken result:{}", JSON.toJSON(authResult));
		if (authResult == null || !authResult.isSuccess() || !authResult.getData()) {
			log.info("parseToken failed");
			requestContext.setSendZuulResponse(false);
			requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
		}
		return null;
	}

	@Override
	public boolean shouldFilter() {
		HttpServletRequest req = RequestContext.getCurrentContext().getRequest();
		log.info("{}, {}", ignoreUrl, req.getRequestURI());
		return !StringUtils.contains(ignoreUrl, req.getRequestURI());
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public String filterType() {
		return "pre";
	}

}
